import matches from 'lodash/matches'

import { BatchEvent } from '@slardar/sdk-template'
import { BrowserConfig } from '@slardar/web'

type Sig = { [k: string]: any }

export const pageUrl = `http://localhost:8080/slardar-lite.html`
export const createPageUrl = (config: Partial<BrowserConfig>, sf: '' | '1' = '', manual: '' | '1' = '') =>
  `http://localhost:8080/slardar-lite.html?config=${JSON.stringify(config)}&sf=${sf}&manual=${manual}`

export const RE_BATCH_REPORT_PATH = /monitor_browser\/collect/

export const filter = (body: Sig, type: string): Sig[] => body?.list?.filter((e: Sig) => e.ev_type === type) || []

export const findAndAssert = findMultiAndAssert.bind(null, 1)
export function findMultiAndAssert(count: number, findFn: (ev: any) => boolean, assertFn: (ev: any) => void) {
  let data = [] as any[]
  function assert(body: BatchEvent<any>) {
    data = data.concat(body?.list?.filter(findFn) || [])
    if (data.length < count) {
      cy.wait('@batch', { timeout: 5000 }).its('request.body').then(assert)
    } else {
      data.forEach(assertFn)
    }
  }
  cy.wait('@batch').its('request.body').then(assert)
}

export const matchAndAssert = matchMultiAndAssert.bind(null, 1)
export function matchMultiAndAssert(count: number, findObj: any, assertFn: (ev: any) => void) {
  findMultiAndAssert(count, matches(findObj), assertFn)
}

export const matchAndMatch = matchMultiAndMatch.bind(null, 1)
export function matchMultiAndMatch(count: number, findObj: any, matchObj: any) {
  findMultiAndAssert(count, matches(findObj), matches(matchObj))
}
